package com.example.bikemanagerjava.common;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class JwtTokenProvider {

    private String jwtSecret = "secret";
    private int jwtExpirationInMs = 86400000; // 24 小时
    private Algorithm algorithm = Algorithm.HMAC512(jwtSecret); // 使用 HMAC512 算法

    // 生成 JWT
    public String generateToken(String username) {
        Date now = new Date();
        Date expiryDate = new Date(now.getTime() + jwtExpirationInMs);

        return JWT.create()
                .withSubject(username) // 设置主题
                .withIssuedAt(now) // 设置签发时间
                .withExpiresAt(expiryDate) // 设置过期时间
                .sign(algorithm); // 使用算法签名
    }

    // 从 JWT 中提取用户名
    public String getUsernameFromToken(String token) {
        DecodedJWT decodedJWT = verifyToken(token);
        return decodedJWT.getSubject();
    }

    // 验证 JWT
    public boolean validateToken(String token) {
        try {
            verifyToken(token);
            return true;
        } catch (JWTVerificationException ex) {
            return false;
        }
    }

    // 解析和验证 JWT
    private DecodedJWT verifyToken(String token) throws JWTVerificationException {
        return JWT.require(algorithm)
                .build()
                .verify(token);
    }
}